package day20170424.ch01;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import org.junit.Test;

public class ObjectStream {
	
	/**
	 * 对象流输入测试
	 */
	@Test
	public void objectInputStreamTest(){
		//小部队
		InputStream is = null;
		//大部队
		ObjectInputStream ois = null;
		try {
			//侦察兵
			File file = new File("txt/student.data");
			//小部队
			is = new FileInputStream(file);
			//大部队
			ois = new ObjectInputStream(is);
			//
			Object readObject = ois.readObject();
			Student student = (Student)readObject;
			System.out.println(student);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally {
			if(null != ois){
				try {
					//关闭大部队
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					if(null != is){
						try {
							//关闭小部队
							is.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
			
		}
	}
	
	/**
	 * 对象流输出测试
	 * @throws Exception
	 */
	@Test
	public void objectOutputStreamTest(){
		//小部队
		OutputStream os = null;
		//大部队
		ObjectOutputStream oos = null;
		try {
			//侦察兵
			File file = new File("txt/student.data");
			//侦察兵告诉小部队路径，小部队去打仗，侦察兵不去
			os = new FileOutputStream(file);
			//大部队跟小部队一起杀敌
			oos = new ObjectOutputStream(os);
			
			//创建一个对象输出
			Student student = new Student();
			student.setName("罗智壕");
			student.setAge(22);
			//写入对象
			oos.writeObject(student);
			//刷新防止堵住
			oos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(null != oos){
				try {
					//关闭大部队
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					if(null != os){
						try {
							//关闭小部队
							os.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		
	}
}
